package com.smart.home.netty.handler;

import com.smart.home.util.ResultCodeResolver;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 无线按钮执行
 *
 * @author zhangpeng
 * @version 1.0
 * @date 2017-03-10
 */
public class WirelessExecuteCommandHandler extends AbstractChannelInboundHandler {

    public WirelessExecuteCommandHandler(String command) {
        setCommand(command);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer(getEncodeCommand()));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        String result = ByteBufUtil.hexDump(msg);
        setStatus(ResultCodeResolver.wirelessExecuteResultStatus(result));
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //TODO 异常处理
        ctx.close();
    }


}
